package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.db.api.FreezeApi;
import com.tanhua.dubbo.db.api.UserInfoApi;
import com.tanhua.dubbo.mongo.api.MovementApi;
import com.tanhua.dubbo.mongo.api.VideoApi;
import com.tanhua.model.db.Freeze;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {


    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private FreezeApi freezeApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public PageResult users(Integer pagesize, Integer page) {

        //返回分页对象,查询所有UserInfo数据
        IPage<UserInfo> iPage=userInfoApi.findAll(page,pagesize);
        //假如返回值的数据列表为空,返回空数据
        if (iPage.getRecords()==null){
            return new PageResult();
        }

        List<UserInfo> infoList = iPage.getRecords();
        //返回数据
        return new PageResult(page,pagesize,iPage.getTotal(),infoList);
    }

    //根据userId查询用户数据,并返回
    public UserInfo findById(Long id) {

        UserInfo userInfo = userInfoApi.findById(id);
        return userInfo;
    }

    //动态分页,
    public PageResult messages(Integer pagesize, Integer page, Long userId, Integer state) {
       //由于该链接不止用在一个页面 所以userId和state可能为空

        //构造一个返回对象 ,list集合和总数
        PageResult result=movementApi.findMovementList(pagesize,page,userId,state);

        if (result==null|| result.getItems()==null){
            return new PageResult();
        }

        //构造返回值
        List<Movement> items = (List<Movement>) result.getItems();
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);

        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<MovementsVo> list=new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = map.get(item.getUserId());
            MovementsVo vo = MovementsVo.init(userInfo, item);
            list.add(vo);
        }
        result.setItems(list);

        //返回
        return result;
    }

    //视频记录翻页
    public PageResult videos(Integer pagesize, Integer page, Long userId) {

        PageResult result=videoApi.findVideoList(page,pagesize,userId);
        if (result==null){
            return new PageResult();
        }

        List<Video> items = (List<Video>) result.getItems();

        UserInfo userInfo = userInfoApi.findById(userId);

        List<VideoVo> vos=new ArrayList<>();
        for (Video item : items) {

            VideoVo vo = VideoVo.init(userInfo, item);
            vos.add(vo);
        }
        result.setItems(vos);

        return result;
    }

    //查询动态
    public MovementsVo findMovement(String id) {
        Movement movement = movementApi.findByMovementId(id);
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());
        MovementsVo vo = MovementsVo.init(userInfo, movement);

        return vo;
    }

    /**
     * 动态审核通过
     *
     * @param ids
     * @return
     */
    public String pass(String[] ids) {
        //通过前端传入的动态id查询动态表中用户信息
        List<Movement> movements = movementApi.selectByIds(ids);
        //遍历数据,获取每一个用户的state状态
        for (Movement movement : movements) {
            //修改state状态
            Integer state = movement.getState();
            if (state == 0) {
                state = 1;
            }
            //获取动态id
            String movementId = movement.getId().toHexString();
            //更新数据库表
            movementApi.updateState(movementId, state);
        }
        //返回数据
        String message = "审核已通过";
        return message;
    }
     //动态拒绝
    public String reject(String[] ids) {
        //通过前端传入的动态id查询动态表中用户信息
        List<Movement> movements = movementApi.selectByIds(ids);
        //遍历数据,获取每一个用户的state状态
        for (Movement movement : movements) {
            //修改state状态为2
            Integer state = movement.getState();
            if (state == 0) {
                state = 2;
            }
            //获取动态id
            String movementId = movement.getId().toHexString();
            //更新数据
            movementApi.updateState(movementId, state);
        }
        //返回数据
        String message = "操作成功";
        return message;
    }
    //冻结用户
    public String freeze(Freeze freeze) {
        //获取需要冻结的用户的id
        Long userId = freeze.getUserId();
        //查询数据库中是否已有
        Freeze isHave = freezeApi.findFreezeByUserId(userId);
        //根据id查询用户信息userInfo
        UserInfo userInfo = userInfoApi.findById(userId);
        if (isHave == null){
            freezeApi.freeze(freeze);
            //设置好用户状态更新到数据库
            userInfo.setUserStatus("2");
            userInfoApi.updateUserInfo(userInfo);
        } else {
            isHave.setFrozenRemarks(freeze.getFrozenRemarks());
            isHave.setReasonsForFreezing(freeze.getReasonsForFreezing());
            isHave.setFreezingTime(freeze.getFreezingTime());
            isHave.setFreezingRange(freeze.getFreezingRange());
            freezeApi.update(isHave);
            //设置好用户状态更新到数据库
            userInfo.setUserStatus("2");
            userInfoApi.updateUserInfo(userInfo);
        }

        String key = Constants.USER_FREEZE+userId;
        String value = freeze.getFreezingTime().toString();  //冻结时间 1三天，2七天 3永久
        if (freeze.getFreezingTime()==1){
            redisTemplate.opsForValue().set(key,value,1,TimeUnit.MINUTES);
        } else if (freeze.getFreezingTime()==2){
            redisTemplate.opsForValue().set(key,value,1*60*24*7,TimeUnit.MINUTES);
        }

        return "操作成功";
    }
    //解冻用户
    public String unfreeze(Integer userId, String reasonsForThawing) {
        //根据id查询用户信息userInfo
        UserInfo userInfo = userInfoApi.findById(Long.valueOf(userId));
        userInfo.setUserStatus("1");
        userInfoApi.updateUserInfo(userInfo);
        String key = Constants.USER_FREEZE+userId;
        redisTemplate.delete(key);
        return "操作成功";
    }
}
